//
//  String+Ext.swift
//  SwiftApp
//
//  Created by ak on 2019/3/10.
//  Copyright © 2019 ak. All rights reserved.
//

import UIKit

public extension String {
  
  func classFromString() -> AnyClass? {
    
    /// get namespace
    let namespace = Bundle.main.infoDictionary?["CFBundleExecutable"] as? String
    guard let prefix = namespace, let cls: AnyClass = NSClassFromString("\(prefix).\(self)") else { return nil }
    
    return cls
  }
  
  func toUIViewController() -> UIViewController? {
    guard let pageCls = self.classFromString() as? UIViewController.Type else { return nil }
    return pageCls.init()
  }
  
  func sizeWith(_ font : UIFont , _ maxSize : CGSize) -> CGSize {
    let options = NSStringDrawingOptions.usesLineFragmentOrigin
    let textBouds = self.boundingRect(with: maxSize,
                                      options: options,
                                      attributes: [NSAttributedString.Key.font: font],
                                      context: nil)
    return textBouds.size
  }
  
  func urlEncode() -> String {
    return self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? self
  }
  
  func urlDecode() -> String {
    return self.removingPercentEncoding ?? self
  }
  
  func urlMethod() -> String? {
    if let url = URL(string: self), let idx = url.absoluteString.lastIndex(of: "/") {
      return String(self[String.Index(encodedOffset: idx.encodedOffset+1)..<self.endIndex])
    }
    return nil
  }
}
